package com.example.rwq_test.delayQueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Description 延迟队列
 *
 * @Author renweiqiang
 * @Date 2024/5/11 上午10:50
 */
public class DelayQueueDemo {
    private static final DelayQueue<DelayedTask> DELAY_QUEUE = new DelayQueue<>();
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                DELAY_QUEUE.put(new DelayedTask("Message 1 " + i, 1000)); // delay of 2 seconds
                DELAY_QUEUE.put(new DelayedTask("Message 2 " + i, 2000)); // delay of 5 seconds
                try {
                    TimeUnit.MILLISECONDS.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        TimeUnit.MILLISECONDS.sleep(10);

        new Thread(() -> {
            while (true) {
                try {
                    DelayedTask task = DELAY_QUEUE.take();
                    System.out.println("Received: " + task.getMessage());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        TimeUnit.MILLISECONDS.sleep(300000);
    }
}
